#include "ShotPlayerStrategy.h"
#include "Weapon.h"
#include "WeaponBank.h"
#include "Bullet.h"
#include "PlayerPlane.h"
#include "MainLayer.h"
#include "MathUtil.h"
#include "Config.h"


ShotPlayerStrategy::ShotPlayerStrategy(void)
{
	_weapon = NULL;
	_numshoot = 0;
	_timeDelay = 0;
}


ShotPlayerStrategy::~ShotPlayerStrategy(void)
{
	CC_SAFE_RELEASE(_weapon);
}

bool ShotPlayerStrategy::init()
{
	if (!BaseStrategy::init())
		return false;

	return true;
}

void ShotPlayerStrategy::processing( float dt )
{

}

void ShotPlayerStrategy::parseXml( xml_node node )
{
	char* weaponKey = (char*)node.child("Weapon").text().as_string();
	setNumShoot(node.child("NumShoot").text().as_int());
	setTimeDelay(node.child("TimeDelay").text().as_float());
	Weapon* wp = WeaponBank::sharedWeaponBank()->getWeapon(weaponKey);
	setWeapon(wp);
}

void ShotPlayerStrategy::onEnter()
{
	BaseStrategy::onEnter();
	schedule(SEL_SCHEDULE(&ShotPlayerStrategy::shoot), _timeDelay, _numshoot - 1, 0);
}

void ShotPlayerStrategy::onExit()
{
	BaseStrategy::onEnter();
	unschedule(SEL_SCHEDULE(&ShotPlayerStrategy::shoot));
}

void ShotPlayerStrategy::shoot( float dt )
{
	if (_weapon)
	{
		CCArray* listBullet =  _weapon->addBullet();
		Bullet* bu = dynamic_cast<Bullet*>(listBullet->objectAtIndex(0));
		PlayerPlane* plane = getOwner()->getMainLayer()->getMyPlant();

		CCPoint directToPlayer = ccp(plane->boundingBox().getMidX() - bu->boundingBox().getMidX(),
									plane->boundingBox().getMidY() - bu->boundingBox().getMidY());
		float angle = MathUtil::angle2Vetor(VECTOR_MAIN, directToPlayer);
		CCObject* it;
		CCARRAY_FOREACH(listBullet, it)
		{
			Bullet* bullet = dynamic_cast<Bullet*>(it);
			bullet->setVelocity(MathUtil::rotateVector(bullet->getVelocity(), angle));
		}
	}
}

Weapon* ShotPlayerStrategy::getWeapon()
{
	return _weapon;
}

void ShotPlayerStrategy::setWeapon(Weapon* var)
{
	if (_weapon != var)
	{
		removeChild(_weapon);
		CC_SAFE_RETAIN(var);
		CC_SAFE_RELEASE(_weapon);
		_weapon = var;
		addChild(_weapon);
	}
}